<?php
namespace app\index\logic;
use think\Db;

class UserBookPoints
{
    /*
     * 获取书点余额
     * @int $uid
     * */
    public function getBalance($uid)
    {
        $time_now = time();

        $money = Db::table('quick_user_book_points')->where('uid',$uid)
                ->where('overdue_time','>',$time_now)->sum('book_point');

        return $money;
    }

    /*
     * 书点消耗
     * @int $uid
     * $int $spend_ficoin 消耗书点
     * */
    public function consume($uid,$spend_ficoin)
    {
        $time_now = time();
        if ($spend_ficoin > 0) {

            $where[] = ['uid', '=', $uid];
            $where[] = ['overdue_time', '>', $time_now];
            $where[] = ['book_point', '>', 0];

            $list = Db::table('quick_user_book_points')->where($where)->field("id,book_point")
                    ->order("overdue_time asc,id asc")->select();

            foreach ($list as $k => $v) {
                if ($spend_ficoin > 0) {
                    if ($v['book_point'] >= $spend_ficoin) {

                        Db::table('quick_user_book_points')->where("id", $v['id'])->setDec('book_point', $spend_ficoin);
                        Db::table('quick_user_book_points')->where("id", $v['id'])->setInc('used_point', $spend_ficoin);

                        //使用书点 > 表内余额才需要减去，不然此表记录还有余额，不能减会变负数
                        $spend_ficoin = $spend_ficoin > $v['book_point'] ? $spend_ficoin - $v['book_point'] : 0;
                        break;

                    } else {
                        //分次消耗
                        Db::table('quick_user_book_points')->where("id", $v['id'])->setDec('book_point', $v['book_point']);
                        Db::table('quick_user_book_points')->where("id", $v['id'])->setInc('used_point', $v['book_point']);
                        $spend_ficoin = $spend_ficoin - $v['book_point'];
                    }
                }
            }

        }

        return $spend_ficoin;
    }

    /**
     * 送书点
     * @param $uid
     * @param $number
     * @param $giveType
     * @param int $continuousDays
     */
    public function givePoint($uid, $number, $giveType,$continuousDays = 1)
    {
        $save = [
            'uid' => $uid,
            'give_type' => $giveType,
            'book_point' => $number,
            'overdue_time' => time() + (86400 * 15),
            'date' => date("Y-m-d"),
            'continuous_days' => $continuousDays
        ];
        Db::table('quick_user_book_points')->insert($save);
    }

}